package com.cet.recon.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.batch.BatchDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author 30952
 */

@Configuration
public class DatasourceConfig {

    // ---------- 业务库 ----------
    @Bean("bizDataSourceProperties")
    @ConfigurationProperties("app.datasource.biz")
    @Primary
    public DataSourceProperties bizDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean("bizDataSource")
    @Primary
    public DataSource bizDataSource(@Qualifier("bizDataSourceProperties") DataSourceProperties bizDataSourceProperties) {
        return bizDataSourceProperties
            .initializeDataSourceBuilder()
            .type(HikariDataSource.class)
            .build();
    }

    @Primary
    @Bean("bizTransactionManager")
    public PlatformTransactionManager bizTransactionManager(@Qualifier("bizDataSource") DataSource bizDataSource) {
        return new DataSourceTransactionManager(bizDataSource);
    }

    @Bean("bizJdbcTemplate")
    public JdbcTemplate bizJdbcTemplate(@Qualifier("bizDataSource") DataSource bizDataSource) {
        return new JdbcTemplate(bizDataSource);
    }

    // ---------- Batch 元数据库 ----------
    @Bean("batchDataSourceProperties")
    @ConfigurationProperties("app.datasource.batch")
    public DataSourceProperties batchDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean("batchDataSource")
    @BatchDataSource
    public DataSource batchDataSource(@Qualifier("batchDataSourceProperties") DataSourceProperties batchDataSourceProperties) {
        return batchDataSourceProperties
            .initializeDataSourceBuilder()
            .type(HikariDataSource.class)
            .build();
    }

    /** 可选：如果你需要显式引用 batch 的事务管理器 */
    @Bean("batchTransactionManager")
    public PlatformTransactionManager batchTransactionManager(@Qualifier("batchDataSource") DataSource batchDataSource) {
        return new DataSourceTransactionManager(batchDataSource);
    }

    @Bean("resourcelessTransactionManager")
    public PlatformTransactionManager resourcelessTransactionManager() {
        return new ResourcelessTransactionManager();
    }
}
